package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    /**
     * 注入客户端需要的对象
     */
    @Autowired
    RestHighLevelClient client;

    /**
     * 根据用户传递的关键字查询数据
     * @param requestParams
     * @return
     */
    @Override
    public PageResult search(RequestParams requestParams) {

        //获取用户传递的数据  搜索的值   每页条数  页数  排序规则
        String key = requestParams.getKey();
        Integer page = requestParams.getPage();
        Integer size = requestParams.getSize();
        String city = requestParams.getCity();
        String brand = requestParams.getBrand();
        String starName = requestParams.getStarName();
        Integer maxPrice = requestParams.getMaxPrice();
        Integer minPrice = requestParams.getMinPrice();
        String location = requestParams.getLocation();



        //获取请求
        SearchRequest request = new SearchRequest("hotel");
        //根据评价排序
        if (requestParams.getSortBy().equals("score")){
            request.source().sort("score",SortOrder.DESC);
        }
        //按照价格排序
        if (requestParams.getSortBy().equals("price")){
            request.source().sort("price",SortOrder.ASC);
        }
        //获取条件查询的对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //判断key是否为空
        if (StringUtils.isNotBlank(key)){
            // 分词 查询
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }

        //精确城市   平拍   星际
        if (StringUtils.isNotBlank(city)){
            boolQuery.filter(QueryBuilders.termQuery("city",city));
        }
        if (StringUtils.isNotBlank(brand)){
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }
        if (StringUtils.isNotBlank(starName)){
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        if (minPrice!= null&& maxPrice != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice).lt(maxPrice));
        }
        //放多重查询的对象封装到请求对象中
        request.source().query(boolQuery);

        //按照距离排序
        if (StringUtils.isNotBlank(location)){
            request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }

        //竞价排名
        FunctionScoreQueryBuilder  functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //指定需要加分的人
                                QueryBuilders.termQuery("id","1902197537"),
                                //将分数改成100
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }); //默认原始分数和定义的分数相乘
        request.source().query(functionScoreQuery);


        //设置高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));


        //分页
        request.source().from((page-1)*size).size(size);
        //定义解析响应
        //返回数据
        return handleResponse(request);
    }



    /**
     * 解析结果
     * @param request
     * @return
     */
    private PageResult handleResponse(SearchRequest request) {
        //发送请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取查询的数据个数
            long value = response.getHits().getTotalHits().value;
            //创建一个集合存储数据
            List<HotelDoc> list = new ArrayList<>();
            //获取具体数据
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                //获取每一个元素
                String sourceAsString = hit.getSourceAsString();
                //将每一个元素反json化
                HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);

                //获取酒店的距离
                Object[] sortValues = hit.getSortValues();
                //如果返回的数据长度>0 表示有数据  将0号数据封装到实体类对象中
                if (sortValues!=null && sortValues.length>0){
                    hotelDoc.setDistance(sortValues[0]);
                }

                //高亮解析
                //解析高亮   高亮的数据是个集合  key 是name  value是个数组
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields.size()>0  ){
                    //获取对应key的value
                    HighlightField name = highlightFields.get("name");
                    if (name!=null ){
                        String s = name.getFragments()[0].toString();
                        hotelDoc.setName(s);
                    }
                }

//                if (!CollectionUtils.isEmpty(highlightFields)) {
//                    // 根据字段名获取高亮结果
//                    HighlightField highlightField = highlightFields.get("name");
//                    if (highlightField != null) {
//                        // 获取高亮值
//                        String name = highlightField.getFragments()[0].string();
//                        // 覆盖非高亮结果
//                        hotelDoc.setName(name);
//                    }
//                }
                //封装到集合中
                list.add(hotelDoc);
            }
            //封装数据返回
            return new PageResult(value,list);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
